//
//  CategoriesTableViewController.m
//  OneDay
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 oneDay. All rights reserved.
//

#import "CategoriesTableViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import "CategoriesTableViewCell.h"
#import "LoginViewController.h"

@interface CategoriesTableViewController ()<collectionCategoryVideoDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSString *string;

@end

@implementation CategoriesTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 没有数据的时候为白色，没有线条
    self.tableView.separatorStyle = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.87 green:0.89 blue:0.88 alpha:1];
    
    [self setUpData];
    [self refreshTableViewData];
    [self addBackButton];
}

// 添加返回按钮
- (void)addBackButton
{
    UIBarButtonItem *leftB = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-reply-3.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBar:)];
    self.navigationItem.leftBarButtonItem = leftB;
}
- (void)backBar:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)setUpData
{
    NSString *tempStr;
    switch (self.row) {
        case 0:
        {
            tempStr = kDesignUrl;
            break;
        }
        case 1:
        {
            tempStr = kSportsUrl;
            break;
        }
        case 2:
        {
            tempStr = kTravelUrl;
            break;
        }
        case 3:
        {
            tempStr = kPlotUrl;
            break;
        }
        case 4:
        {
            tempStr = kAnimationUrl;
            break;
        }
        case 5:
        {
            tempStr = kAdvertisementUrl;
            break;
        }
        case 6:
        {
            tempStr = kMusicUrl;
            break;
        }
        case 7:
        {
            tempStr = kAppetiteUrl;
            break;
        }
        case 8:
        {
            tempStr = kNoticeUrl;
            break;
        }
        case 9:
        {
            tempStr = kSynthesizeUrl;
            break;
        }
        case 10:
        {
            tempStr = kRecordUrl;
            break;
        }
        case 11:
        {
            tempStr = kFashionUrl;
            break;
        }
        default:
            break;
    }
    self.dataArray = [NSMutableArray array];
    [self requestCategoryDataWithUrl:tempStr block:^(NSArray *array) {
        [self.dataArray addObjectsFromArray:array];
        [self.tableView reloadData];
    }];
}

// 拼接Url
- (NSString *)returnAppendingUrl:(NSString *)url
{
    NSLog(@"%@", self.string);
    NSArray *strArray1 = [url componentsSeparatedByString:@"?"];
    NSArray *strArray2 = [self.string componentsSeparatedByString:@"&"];
    NSString *strUrl = [strArray2.firstObject stringByAppendingFormat:@"&%@", strArray1.lastObject];
    return strUrl;
}

#pragma mark - tableView 刷新
- (void)refreshTableViewData
{
    // 下拉刷新
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    // 进入刷新状态
    [self.tableView.header beginRefreshing];
}

- (void)footerRefresh
{
    NSString *tempStr;
    switch (self.row) {
        case 0:
        {
            tempStr = [self returnAppendingUrl:kDesignUrl];
            break;
        }
        case 1:
        {
            tempStr = [self returnAppendingUrl:kSportsUrl];
            break;
        }
        case 2:
        {
            tempStr = [self returnAppendingUrl:kTravelUrl];
            break;
        }
        case 3:
        {
            tempStr = [self returnAppendingUrl:kPlotUrl];
            break;
        }
        case 4:
        {
            tempStr = [self returnAppendingUrl:kAnimationUrl];
            break;
        }
        case 5:
        {
            tempStr = [self returnAppendingUrl:kAdvertisementUrl];
            break;
        }
        case 6:
        {
            tempStr = [self returnAppendingUrl:kMusicUrl];
            break;
        }
        case 7:
        {
            tempStr = [self returnAppendingUrl:kAppetiteUrl];
            break;
        }
        case 8:
        {
            tempStr = [self returnAppendingUrl:kNoticeUrl];
            break;
        }
        case 9:
        {
            tempStr = [self returnAppendingUrl:kSynthesizeUrl];
            break;
        }
        case 10:
        {
            tempStr = [self returnAppendingUrl:kRecordUrl];
            break;
        }
        case 11:
        {
            tempStr = [self returnAppendingUrl:kFashionUrl];
            break;
        }
        default:
            break;
    }
    [self requestCategoryDataWithUrl:tempStr block:^(NSArray *array) {
        [self.dataArray addObjectsFromArray:array];
        [self.tableView reloadData];
    }];
    [self.tableView.footer endRefreshing];
    
}

- (void)headerRefresh
{
    // 在这个方法中请求数据
    // 结束刷新状态
    [self.tableView.header endRefreshing];
}

#pragma mark - Table view data source
// 返回分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
// 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kHeight / 2.26 + 5;
}
// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CategoriesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"categoryTableViewCell"];
    
    if (cell == nil) {
        cell = [[CategoriesTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"categoryTableViewCell"];
    }
    
    if (self.dataArray.count != 0) {
        cell.model = self.dataArray[indexPath.row];
    }
    cell.delegate = self;
    [cell.shareButton addTarget:self action:@selector(shareVideoModel:) forControlEvents:UIControlEventTouchUpInside];
    [cell.shareLabel addTarget:self action:@selector(shareVideoModelTwo:) forControlEvents:UIControlEventTouchUpInside];
    cell.shareButton.tag = indexPath.row + 300;
    cell.shareLabel.tag = indexPath.row + 700;
    return cell;
}

// 收藏
- (void)collectionCellDidSelected:(VideoModel *)model
{
    UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:nil message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    DataManager *manager = [DataManager shareManager];
    // 判断是否登录
    if ([manager isLogin] == NO) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        
        // 实现block
        loginVC.block = ^void(){
            NSLog(@"登录成功");
        };
        
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navC animated:YES completion:nil];
    }else{
        LeanCloudObject *leanCloud = [[LeanCloudObject alloc] init];
        NSString *userName = [manager userName];
        NSLog(@"%@", userName);
        // 先判断是否收藏过
        NSArray *videoArray = [leanCloud selectStundetWithStyle:@"video" userName:userName];
        BOOL isHave = NO;
        for (VideoObject *video in videoArray) {
            if ([video.title isEqualToString:model.title]) {
                isHave = YES;
                break;
            }
        }
        if (isHave == NO) {
            [leanCloud creatObjectWithTitle:model.title imageUrl:model.coverForDetail needString:model.playUrl style:@"video" userName:userName];
            [alertView show];
        }else{
            alertView.message = @"您已经收藏过了";
            [alertView show];
        }
        // 实现 2 秒回收
        [self performSelector:@selector(actionAlert:) withObject:alertView afterDelay:2];
    }
}
#pragma mark -- 实现2秒消失
- (void)actionAlert:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];// 三秒回收
}


// 分享
- (void)shareVideoModel:(UIButton *)sender
{
    NSLog(@"分享");
    VideoModel *model = self.dataArray[sender.tag - 300];
    // 需要分享的文字
    NSString *str = [NSString stringWithFormat:@"OneDay推荐：%@，精彩微视频请看：%@", model.title, model.playUrl];
    // 图片
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.coverForDetail] placeholderImage:nil];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56396d0ee0f55aff4d0010a0"
                                      shareText:str
                                     shareImage:imageView.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent, UMShareToDouban,UMShareToEmail,UMShareToFacebook, nil]
                                       delegate:nil];
}

- (void)shareVideoModelTwo:(UIButton *)sender
{
    NSLog(@"分享");
    VideoModel *model = self.dataArray[sender.tag - 700];
    // 需要分享的文字
    NSString *str = [NSString stringWithFormat:@"OneDay推荐：%@，精彩微视频请看：%@", model.title, model.playUrl];
    // 图片
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.coverForDetail] placeholderImage:nil];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56396d0ee0f55aff4d0010a0"
                                      shareText:str
                                     shareImage:imageView.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent, UMShareToDouban,UMShareToEmail,UMShareToFacebook, nil]
                                       delegate:nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoModel *model = self.dataArray[indexPath.row];
    [self playVideoWithModel:model];
}

- (void)playVideoWithModel:(VideoModel *)model
{
    // 播放路径
    NSURL *url = [NSURL URLWithString:[model.playUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    AVPlayer *player = [AVPlayer playerWithURL:url];
    AVPlayerViewController *playerVC = [AVPlayerViewController new];
    playerVC.player = player;
    [self presentViewController:playerVC animated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}


#pragma mark - 各个种类的数据请求
- (void)requestCategoryDataWithUrl:(NSString *)url block:(void (^)(NSArray *array))block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [request setHTTPMethod:@"GET"];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            // 保护方法
            if (data == nil) {
                return ;
            }
            
            NSDictionary *rootDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            
            // 下页的拼接网址
            self.string = rootDictionary[@"nextPageUrl"];
            
            NSArray *tempArray = rootDictionary[@"videoList"];
            
            // 数组初始化
            NSMutableArray *array = [NSMutableArray array];
            // 遍历数组
            for (NSDictionary *dic in tempArray) {
                VideoModel *model = [[VideoModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [array addObject:model];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                block(array);
            });
        }];
        [dataTask resume];
    });
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
